/*
 * Copyright (C) 2011 by Fabien Barbero
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.flickr.api.auth;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthException;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.util.Log;

/**
 *
 * @author Fabien Barbero
 */
public class OAuthHandler {
    
    private static final String TAG = OAuthHandler.class.getSimpleName();
    
    public static final Uri CALLBACK_URI = Uri.parse("flickr://auth-access-token.com");
    public static final String EXTRA_NAME = "oauth.handler";
    
    public static final String API_KEY = "5fbc338cfc38ea38cd3bfa914cf5f724";
    public static final String API_SECRET = "e9115bb744360290";
    
    private static final String REQUEST_TOKEN_KEY = "oauth.request.token";
    private static final String REQUEST_SECRET_KEY = "oauth.request.secret";
    private static final String ACCESS_TOKEN_KEY = "oauth.access.token";
    private static final String ACCESS_SECRET_KEY = "oauth.access.secret";

    private static OAuthHandler instance;
    
    private final OAuthConsumer consumer;
    private final OAuthProvider provider;
    
    private OAuthToken requestToken;
    private OAuthToken accessToken;

    private SharedPreferences prefs;

    private Context mContext;
    
    
    public static void initInstance(Context context) {
        if(instance == null) {
            instance = new OAuthHandler(context);
        }
    }
    
    public static OAuthHandler getHandler() {
        return instance;
    }
    
    private OAuthHandler(Context context) {
        mContext = context;
        
        consumer = new CommonsHttpOAuthConsumer(API_KEY, API_SECRET);
        provider = new CommonsHttpOAuthProvider("http://www.flickr.com/services/oauth/request_token",
                                                "http://www.flickr.com/services/oauth/access_token",
                                                "http://www.flickr.com/services/oauth/authorize");
        provider.setOAuth10a(true);
    }
    
    public void load(SharedPreferences prefs) {
        this.prefs = prefs;
        if(prefs.contains(REQUEST_TOKEN_KEY) && prefs.contains(REQUEST_SECRET_KEY)) {
            requestToken = new OAuthToken(prefs.getString(REQUEST_TOKEN_KEY, null), prefs.getString(REQUEST_SECRET_KEY, null));
            setToken(requestToken);
            Log.d(TAG, "Request token loaded");
            
        } else if(prefs.contains(ACCESS_TOKEN_KEY) && prefs.contains(ACCESS_SECRET_KEY)) {
            accessToken = new OAuthToken(prefs.getString(ACCESS_TOKEN_KEY, null), prefs.getString(ACCESS_SECRET_KEY, null));
            setToken(accessToken);
            Log.d(TAG, "Access token loaded");
        }
    }
    
    private void setToken(OAuthToken token) {
        consumer.setTokenWithSecret(token.getKey(), token.getSecret());
    }
    
    private void save() {
        if(prefs == null) {
            Log.w(TAG, "Unable to save OAuth data because no SharedPreference defined");
            return;
        }
        
        if(prefs != null) {
            Editor editor = prefs.edit();
            if(requestToken != null) {
                editor.putString(REQUEST_TOKEN_KEY, requestToken.getKey());
                editor.putString(REQUEST_SECRET_KEY, requestToken.getSecret());
                Log.d(TAG, "Request token saved");
            } else {
                editor.remove(REQUEST_TOKEN_KEY);
                editor.remove(REQUEST_SECRET_KEY);
                Log.d(TAG, "Request token removed");
            }
            
            if(accessToken != null) {
                editor.putString(ACCESS_TOKEN_KEY, accessToken.getKey());
                editor.putString(ACCESS_SECRET_KEY, accessToken.getSecret());
                Log.d(TAG, "Access token saved");
            } else {
                editor.remove(ACCESS_TOKEN_KEY);
                editor.remove(ACCESS_SECRET_KEY);
                Log.d(TAG, "Access token removed");
            }
            editor.commit();
        }
    }
    
    public OAuthToken getAccessToken()
    {
        return accessToken;
    }
    
    public OAuthToken getRequestToken()
    {
        return requestToken;
    }

    public OAuthConsumer getConsumer()
    {
        return consumer;
    }
    
    public String retrieveAuthorizationUrl() throws OAuthException {
        String authorizationUrl = provider.retrieveRequestToken(consumer, CALLBACK_URI.toString());
        requestToken = new OAuthToken(consumer.getToken(), consumer.getTokenSecret());
        save();
        Log.d(TAG, "Request token retrieved");
        return authorizationUrl;
    }
    
    public void retrieveAccessToken(String verifier) throws OAuthException {
        provider.retrieveAccessToken(consumer, verifier);
        Log.d(TAG, "Access token retrieved");
        accessToken = new OAuthToken(consumer.getToken(), consumer.getTokenSecret());
        requestToken = null; // Invalidate
        save();
    }
    
    public void clear() {
        requestToken = null;
        accessToken = null;
        Log.d(TAG, "OAuthHandler cleaned");
        save();
    }

    @Override
    public String toString()
    {
        return "key=" + API_KEY + ", secret=" + API_SECRET;
    }

}
